#pragma once

#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <unistd.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include"pthreadpoul.hpp"
#include"InetAddr.hpp"
#include "nocopy.hpp"
#include "log.hpp"
#include "Comm.hpp"
#include <pthread.h>
#include<functional>
using namespace std;
const uint16_t defoultport = 8888;
const static int defaultfd = -1;
const int defaultsize = 1024;
using task_t = std::function<void()>;


class Udpserver : public nocopy
{
public:
     Udpserver(uint16_t port = defoultport)
    :_port(port)
    {
        pthread_mutex_init(&_user_mutex,nullptr);
    }
    void Init()
    {
        // 1. 创建socket，就是创建了文件细节
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            lg.massage(Fatal, "socket errr,%d:%s\n", errno, strerror(errno));
            exit(Socket_Err);
        }
        lg.massage(Info, "socket success, sockfd: %d\n", _sockfd);
       // 2. 绑定，指定网络信息
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = 0;
        //  local.sin_addr.s_addr = inet_addr(_ip.c_str());
        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        // 结构体填完，设置到内核中了吗？？没有
        if (n != 0)
        {
            lg.massage(Fatal, "bind_rr %d:%s\n", errno, strerror(errno));
            exit(Bind_Err);
        }
         Threadpool<task_t>::GetInstance()->start();
    }
    void adduser(InetAddr addr)
    {
           LockGuard lockguard(&_user_mutex);
           for(auto &user:_online_user)
           {
            if(user==addr)
                return;
           }
            _online_user.push_back(addr);
             lg.massage(Debug,"%s:%d is add to onlineuser list...\n", addr.Ip().c_str(), addr.Port() );
    }
    void Route(int _sock,string &message)
    {
        LockGuard lockguard(&_user_mutex);
        for(auto &user:_online_user)
        {
            sendto(_sockfd, message.c_str(),message.size(), 0, (struct sockaddr *)&user.Getaddr(), sizeof(user.Getaddr()));
            lg.massage(Debug, "server send message to %s:%d, message: %s\n", user.Ip().c_str(), user.Port(), message.c_str());
        }
    }
    void Start()
    {
        char buffer[defaultsize];
        // 服务器永远不退出
        for (;;)
        {

            struct sockaddr_in peer;
            
            socklen_t len = sizeof(peer);//不能乱写
            
            //ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                buffer[n]=0;
                InetAddr addr(peer);
                std::string message = "[";
                message += addr.Ip();
                message += ":";
                message += std::to_string(addr.Port());
                message += "]# ";
                message += buffer;
                adduser(addr);
                 //std::cout << "[" << addr.PrintDebug() << "]# " << buffer << std::endl;
                //std::cout << "client sar# :" << buffer << std::endl;
                task_t task = std::bind(&Udpserver::Route, this, _sockfd, message);
                Threadpool<task_t>::GetInstance()->push(task);
              
            }
        }
    }

    ~Udpserver()
    {
    }

private:
     //std::string _ip;
    uint16_t _port;
    int _sockfd;
          vector<InetAddr>_online_user;
          pthread_mutex_t _user_mutex;

};